package com.uxsino.simo.indicator.retractor;

import com.google.common.collect.Maps;
import com.google.common.primitives.Doubles;
import com.uxsino.reactorq.model.INDICATOR_TYPE;
import com.uxsino.simo.networkentity.EntityInfo;
import com.uxsino.simo.query.QueryContext;
import com.uxsino.simo.query.QueryTemplate;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public class SNMPMapMaxValueRetractor extends SNMPMapSumValueRetractor {
    public SNMPMapMaxValueRetractor(){
        super();
    }


    @SuppressWarnings("unchecked")
    @Override
    public Object doRetract(EntityInfo entity, QueryContext ctxt, QueryTemplate qt, Object obj) {
        Map<String, Object> record = Maps.newHashMap();
        if (obj == null) {
            return record;
        }
        Map<String, Map<String, String>> map = (Map<String, Map<String, String>>) obj;

        //获取field交集
        List<String> ids = fieldMapping.values().stream().collect(Collectors.toList());
        ids.retainAll(map.keySet());

        if(ids.isEmpty()){
            return record;
        }

        //组装数据
        for (Map.Entry<String, IValueRetractor> entry : fieldRetrievers.entrySet()) {
            if(ids.contains(fieldMapping.get(entry.getKey()))){
                if(INDICATOR_TYPE.NUMBER.equals(entry.getValue().getValueType()) || INDICATOR_TYPE.PERCENT.equals(entry.getValue().getValueType())){
                    Optional<Double> result = map.get(fieldMapping.get(entry.getKey())).values().parallelStream().map(v->{
                        try {
                            return Doubles.tryParse(v);
                        } catch (Exception e) {
                            return null;
                        }
                    }).filter(v->v != null).max(Comparator.naturalOrder());
                    if(result.isPresent()){
                        record.put(entry.getKey(), result.get());
                    }
                }
            }
        }
        return record;
    }
}
